
import router, { asyncRoutes } from './router'
import store from '@/store'
import NProgress from 'nprogress'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const whiteList = ['/login', '/404', '/abc']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    // 如果访问的是login,就直接进入主页
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      //
      if (!store.getters.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log('当前用户一起可以访问', res.roles.menus, asyncRoutes)
        const filtereRoutes = asyncRoutes.filter(item => {
          return res.roles.menus.includes(item.children[0].name)
        })
        filtereRoutes.push({ path: '*', redirect: '/404', hidden: true })
        store.commit('menu/setMenus', filtereRoutes)
        router.addRoutes(filtereRoutes)
        // 白屏
        next(to)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      // console.log('22')
      next()
    } else {
      // console.log('33')
      next('/login')
    }
  }
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  next()
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
